package com.ding.dailyup.controller;

import javax.servlet.http.HttpServletRequest;

import com.ding.dailyup.annotation.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ding.dailyup.entity.JsonResult;
import com.ding.dailyup.entity.UserEntity;
import com.ding.dailyup.entity.WxUserInfoEntity;
import com.ding.dailyup.entity.request.WxLoginReq;
import com.ding.dailyup.exception.ParamException;
import com.ding.dailyup.service.UserCollectStrategyService;
import com.ding.dailyup.service.UserService;
import com.ding.dailyup.util.IpUtil;
import com.ding.dailyup.util.UserTokenUtil;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/wx/auth")
@Api(tags = "微信授权")
@Slf4j
public class WxAuthController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserCollectStrategyService userCollectStrategyService;

	@PostMapping("/login")
	@ApiOperation(value = "微信登录")
	public JsonResult<UserEntity> loginByWx(@RequestBody WxLoginReq wxLoginInfo,
			HttpServletRequest request) {
		String code = wxLoginInfo.getCode();
		WxUserInfoEntity wxUserInfoEntity = wxLoginInfo.getUserInfo();
		if (StrUtil.isEmpty(code) || ObjectUtil.isNull(wxUserInfoEntity)) {
			throw new ParamException("参数异常!");
		}

		UserEntity user = userService.saveWxUser(wxLoginInfo.getCode(),
				IpUtil.getIpAddr(request), wxLoginInfo.getUserInfo());
		user.setToken(UserTokenUtil.generateToken(user.getId().intValue()));

		if (user.isRegister()) {
			// 生成默认的收藏策略
			userCollectStrategyService.collectDefaultStrategy(user.getId());
		}
		return JsonResult.succResult(user);
	}

	@GetMapping("/strategyNumber")
	@ApiOperation("用户策略次数")
	public JsonResult getUserInfo(@LoginUser Long userId) {
		if (UserTokenUtil.isLogin(userId)) {
			return JsonResult.succResult(userService.findById(userId));
		} else {
			return JsonResult.succResult(0);
		}
	}

	@PostMapping("/logout")
	@ApiOperation(value = "微信登出")
	public JsonResult loginByWx() {
		return JsonResult.succResult();
	}
}
